package com.harmony.pilot.agent.tools;

import com.harmony.pilot.agent.model.ConversationContext;
import com.harmony.pilot.agent.model.Intent;
import com.harmony.pilot.agent.model.ToolRequest;
import com.harmony.pilot.agent.model.ToolResult;
import com.harmony.pilot.agent.service.LLMServiceClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * OpenHarmony API工具
 * 帮助用户查找和调用OpenHarmony组件的能力
 */
@Component
@Slf4j
public class OpenHarmonyAPITool implements AgentTool {
    
    private final LLMServiceClient llmServiceClient;
    private final RestTemplate restTemplate;
    
    @Value("${service.data.url:http://localhost:8085}")
    private String dataServiceUrl;
    
    public OpenHarmonyAPITool(LLMServiceClient llmServiceClient, 
                             @Autowired(required = false) RestTemplate restTemplate) {
        this.llmServiceClient = llmServiceClient;
        this.restTemplate = restTemplate != null ? restTemplate : new RestTemplate();
    }
    
    @Override
    public String getName() {
        return "openharmony_api";
    }
    
    @Override
    public String getDescription() {
        return "查找和调用OpenHarmony组件的能力（如包管理、Samgr、分布式数据等），提供完整的代码示例";
    }
    
    @Override
    public String getParametersSchema() {
        return """
            {
              "type": "object",
              "properties": {
                "requirement": {
                  "type": "string",
                  "description": "用户需求描述，如'我要调用包管理的安装能力'、'调用Samgr的注册能力'"
                },
                "component": {
                  "type": "string",
                  "description": "组件名称（可选，如果不提供会自动识别）"
                },
                "capability": {
                  "type": "string",
                  "description": "具体能力描述（可选，如'安装'、'注册'、'查询'）"
                }
              },
              "required": ["requirement"]
            }
            """;
    }
    
    @Override
    public boolean canHandle(Intent intent, ConversationContext context) {
        // 检查意图类型和动作
        if (intent.getType() == Intent.IntentType.CODE_GENERATION && 
            "openharmony_api".equals(intent.getAction())) {
            return true;
        }
        
        // 检查用户消息
        String userMessage = context.getUserMessage();
        if (userMessage == null) {
            return false;
        }
        
        String lowerMessage = userMessage.toLowerCase();
        
        // 检查是否提到OpenHarmony组件
        return lowerMessage.contains("包管理") || 
               lowerMessage.contains("samgr") ||
               lowerMessage.contains("系统能力") ||
               lowerMessage.contains("分布式") ||
               (lowerMessage.contains("调用") && (
                   lowerMessage.contains("能力") || 
                   lowerMessage.contains("api") ||
                   lowerMessage.contains("功能")
               ));
    }
    
    @Override
    public double getRelevanceScore(Intent intent, ConversationContext context) {
        if (canHandle(intent, context)) {
            String userMessage = context.getUserMessage();
            if (userMessage == null) {
                return 0.7;
            }
            
            String lowerMessage = userMessage.toLowerCase();
            
            // 如果明确提到OpenHarmony组件，提高分数
            if (lowerMessage.contains("包管理") || lowerMessage.contains("samgr")) {
                return 0.95;
            }
            
            if (lowerMessage.contains("调用") && lowerMessage.contains("能力")) {
                return 0.85;
            }
            
            return 0.7;
        }
        return 0.0;
    }
    
    @Override
    public ToolResult execute(ToolRequest request) {
        Map<String, Object> params = request.getParameters();
        if (params == null) {
            params = new HashMap<>();
        }
        
        String requirement = (String) params.get("requirement");
        if (requirement == null || requirement.isEmpty()) {
            requirement = request.getContext().getUserMessage();
            if (requirement == null) {
                requirement = "";
            }
        }
        
        String component = (String) params.get("component");
        String capability = (String) params.get("capability");
        
        try {
            // 1. 识别组件
            List<ComponentMatch> matches = identifyComponents(requirement);
            
            if (matches.isEmpty()) {
                return ToolResult.error("未识别到相关OpenHarmony组件。请提供更具体的描述，例如：\n" +
                    "- 我要调用包管理的安装能力\n" +
                    "- 调用Samgr的注册系统能力\n" +
                    "- 使用分布式数据存储");
            }
            
            // 2. 查询组件API
            ComponentMatch bestMatch = matches.get(0);
            List<ComponentAPI> apis = queryComponentAPIs(
                component != null ? component : bestMatch.getComponentName(),
                capability != null ? capability : requirement
            );
            
            if (apis.isEmpty()) {
                return ToolResult.error("未找到相关API。组件: " + bestMatch.getComponentName());
            }
            
            // 3. 生成完整的调用代码
            String codeExample = generateCompleteCodeExample(
                bestMatch.getComponentName(),
                apis.get(0),
                request.getContext()
            );
            
            // 4. 构建响应
            Map<String, Object> data = new HashMap<>();
            data.put("component", bestMatch.getComponentName());
            data.put("componentDescription", bestMatch.getComponentInfo().getDescription());
            data.put("apis", apis);
            data.put("recommendedAPI", apis.get(0));
            data.put("codeExample", codeExample);
            
            StringBuilder message = new StringBuilder();
            message.append("✅ 已找到OpenHarmony组件：**").append(bestMatch.getComponentName()).append("**\n\n");
            message.append("📝 组件描述：").append(bestMatch.getComponentInfo().getDescription()).append("\n\n");
            message.append("🔧 推荐API：").append(apis.get(0).getName()).append("\n");
            if (apis.get(0).getDescription() != null) {
                message.append("   ").append(apis.get(0).getDescription()).append("\n");
            }
            message.append("\n");
            message.append("💻 完整代码示例：\n");
            message.append("```cpp\n");
            message.append(codeExample);
            message.append("\n```\n\n");
            
            if (apis.size() > 1) {
                message.append("📚 其他可用API（共").append(apis.size()).append("个）：\n");
                for (int i = 1; i < Math.min(5, apis.size()); i++) {
                    message.append("- ").append(apis.get(i).getName());
                    if (apis.get(i).getQualifiedName() != null) {
                        message.append(" (").append(apis.get(i).getQualifiedName()).append(")");
                    }
                    message.append("\n");
                }
            }
            
            return ToolResult.success(message.toString(), data);
            
        } catch (Exception e) {
            log.error("Failed to execute OpenHarmony API tool", e);
            return ToolResult.error("查询OpenHarmony API失败: " + e.getMessage());
        }
    }
    
    /**
     * 识别组件
     */
    private List<ComponentMatch> identifyComponents(String requirement) {
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("message", requirement);
            
            Map<String, Object> response = restTemplate.postForObject(
                dataServiceUrl + "/data/openharmony/component/identify",
                request,
                Map.class
            );
            
            if (response != null && "200".equals(String.valueOf(response.get("code")))) {
                List<Map<String, Object>> matchesData = (List<Map<String, Object>>) response.get("data");
                List<ComponentMatch> matches = new ArrayList<>();
                
                if (matchesData != null) {
                    for (Map<String, Object> matchData : matchesData) {
                        ComponentMatch match = new ComponentMatch();
                        match.setComponentName((String) matchData.get("componentName"));
                        match.setScore(((Number) matchData.get("score")).doubleValue());
                        matches.add(match);
                    }
                }
                
                return matches;
            }
        } catch (Exception e) {
            log.error("Failed to identify components", e);
        }
        
        return new ArrayList<>();
    }
    
    /**
     * 查询组件API
     */
    private List<ComponentAPI> queryComponentAPIs(String componentName, String capability) {
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("componentName", componentName);
            request.put("capability", capability);
            
            Map<String, Object> response = restTemplate.postForObject(
                dataServiceUrl + "/data/openharmony/component/apis",
                request,
                Map.class
            );
            
            if (response != null && "200".equals(String.valueOf(response.get("code")))) {
                List<Map<String, Object>> apisData = (List<Map<String, Object>>) response.get("data");
                List<ComponentAPI> apis = new ArrayList<>();
                
                if (apisData != null) {
                    for (Map<String, Object> apiData : apisData) {
                        ComponentAPI api = new ComponentAPI();
                        api.setName((String) apiData.get("name"));
                        api.setQualifiedName((String) apiData.get("qualifiedName"));
                        api.setReturnType((String) apiData.get("returnType"));
                        api.setParameters((String) apiData.get("parameters"));
                        api.setDescription((String) apiData.get("description"));
                        api.setExample((String) apiData.get("example"));
                        api.setFilePath((String) apiData.get("filePath"));
                        if (apiData.get("lineNumber") != null) {
                            api.setLineNumber(((Number) apiData.get("lineNumber")).intValue());
                        }
                        api.setModulePath((String) apiData.get("modulePath"));
                        api.setGnDepPath((String) apiData.get("gnDepPath"));
                        if (apiData.get("isCrossModule") != null) {
                            api.setCrossModule(Boolean.parseBoolean(apiData.get("isCrossModule").toString()));
                        }
                        if (apiData.get("requiredHeaders") != null) {
                            @SuppressWarnings("unchecked")
                            List<String> headers = (List<String>) apiData.get("requiredHeaders");
                            api.setRequiredHeaders(headers);
                        }
                        apis.add(api);
                    }
                }
                
                return apis;
            }
        } catch (Exception e) {
            log.error("Failed to query component APIs", e);
        }
        
        return new ArrayList<>();
    }
    
    /**
     * 生成完整的代码示例
     */
    private String generateCompleteCodeExample(String componentName, ComponentAPI api, ConversationContext context) {
        StringBuilder code = new StringBuilder();
        
        // 1. 添加头文件
        code.append("// 使用").append(componentName).append("的").append(api.getName()).append("功能\n");
        
        // 添加必要的头文件
        if (api.getRequiredHeaders() != null && !api.getRequiredHeaders().isEmpty()) {
            for (String header : api.getRequiredHeaders()) {
                code.append("#include \"").append(header).append("\"\n");
            }
        } else {
            code.append("#include \"").append(api.getName()).append(".h\"\n");
        }
        code.append("#include <iostream>\n");
        code.append("#include <memory>\n\n");
        
        // 2. 添加命名空间
        if (api.getQualifiedName() != null && api.getQualifiedName().contains("::")) {
            String namespace = api.getQualifiedName().substring(0, api.getQualifiedName().lastIndexOf("::"));
            code.append("using namespace ").append(namespace).append(";\n\n");
        }
        
        // 3. 生成函数示例
        code.append("void example").append(api.getName()).append("() {\n");
        code.append("    // 创建").append(componentName).append("实例\n");
        code.append("    auto instance = ");
        
        // 根据API类型生成不同的初始化代码
        if (componentName.contains("包管理")) {
            code.append("BundleMgrClient::GetInstance();\n");
        } else if (componentName.contains("Samgr")) {
            code.append("SystemAbilityManager::GetInstance();\n");
        } else {
            code.append(api.getName()).append("::GetInstance();\n");
        }
        
        code.append("\n");
        code.append("    // 调用").append(api.getName()).append("方法\n");
        
        if (api.getParameters() != null && !api.getParameters().isEmpty()) {
            code.append("    // 参数：").append(api.getParameters()).append("\n");
        }
        
        code.append("    // TODO: 根据实际需求填充参数\n");
        code.append("    // ");
        if (api.getReturnType() != null && !api.getReturnType().equals("void")) {
            code.append(api.getReturnType()).append(" result = ");
        }
        code.append("instance->").append(api.getName()).append("(/* 参数 */);\n");
        
        code.append("\n");
        code.append("    // 处理结果\n");
        if (api.getReturnType() != null && !api.getReturnType().equals("void")) {
            code.append("    // if (result != nullptr) {\n");
            code.append("    //     // 处理返回结果\n");
            code.append("    // }\n");
        }
        
        code.append("}\n");
        
        // 添加GN依赖建议
        if (api.getGnDepPath() != null && !api.getGnDepPath().isEmpty()) {
            code.append("\n");
            code.append("/*\n");
            code.append(" * GN依赖建议：\n");
            code.append(" * 在BUILD.gn文件中添加以下依赖：\n");
            code.append(" * deps = [\n");
            code.append(" *   \"").append(api.getGnDepPath()).append("\",\n");
            code.append(" * ]\n");
            code.append(" */\n");
        }
        
        return code.toString();
    }
    
    // 内部类用于数据传递
    private static class ComponentMatch {
        private String componentName;
        private Map<String, Object> componentInfo;
        private double score;
        
        public String getComponentName() { return componentName; }
        public void setComponentName(String componentName) { this.componentName = componentName; }
        
        public Map<String, Object> getComponentInfo() { return componentInfo; }
        public void setComponentInfo(Map<String, Object> componentInfo) { this.componentInfo = componentInfo; }
        
        public double getScore() { return score; }
        public void setScore(double score) { this.score = score; }
    }
    
    private static class ComponentAPI {
        private String name;
        private String qualifiedName;
        private String returnType;
        private String parameters;
        private String description;
        private String example;
        private String filePath;
        private int lineNumber;
        
        // 跨模块调用信息
        private String modulePath;
        private String gnDepPath;
        private List<String> requiredHeaders;
        private boolean isCrossModule;
        
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        
        public String getQualifiedName() { return qualifiedName; }
        public void setQualifiedName(String qualifiedName) { this.qualifiedName = qualifiedName; }
        
        public String getReturnType() { return returnType; }
        public void setReturnType(String returnType) { this.returnType = returnType; }
        
        public String getParameters() { return parameters; }
        public void setParameters(String parameters) { this.parameters = parameters; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public String getExample() { return example; }
        public void setExample(String example) { this.example = example; }
        
        public String getFilePath() { return filePath; }
        public void setFilePath(String filePath) { this.filePath = filePath; }
        
        public int getLineNumber() { return lineNumber; }
        public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; }
        
        public String getModulePath() { return modulePath; }
        public void setModulePath(String modulePath) { this.modulePath = modulePath; }
        
        public String getGnDepPath() { return gnDepPath; }
        public void setGnDepPath(String gnDepPath) { this.gnDepPath = gnDepPath; }
        
        public List<String> getRequiredHeaders() { return requiredHeaders; }
        public void setRequiredHeaders(List<String> requiredHeaders) { this.requiredHeaders = requiredHeaders; }
        
        public boolean isCrossModule() { return isCrossModule; }
        public void setCrossModule(boolean crossModule) { isCrossModule = crossModule; }
    }
}

